# -*- coding: utf-8 -*-
# @Time    : 2024/8/29 12:07
# @Author  : Alvin
# @File    : session.py
from app.libs.error_code import AuthFailed, ServerError
from app.libs.my_crypto import generate_hmac_sha256_signature
from app.libs.my_http import Http
from app.models.access_tokens import AccessToken


def session_check(session_obj, access_token, open_id):
    session = session_obj.session_token
    print(access_token)
    signature = generate_hmac_sha256_signature(session, '')
    url = f'https://api.weixin.qq.com/wxa/checksession?access_token={access_token}&signature={signature}&openid={open_id}&sig_method=hmac_sha256'
    response = Http.get(url)
    error_code = response.get('errcode', 0)
    if error_code == 42001:
        # session_obj.delete()
        raise AuthFailed(msg="session过期，请重新登录")
    elif error_code == 87009:
        # session_obj.delete()
        raise AuthFailed(msg="无效session签名")
    elif error_code == 40003:
        # session_obj.delete()
        raise AuthFailed("非法oepn_id")
    elif error_code == 40001:
        # session_obj.delete()
        # TODO: 完善这个access_token的更新机制
        AccessToken.delete_token(access_token)
        raise ServerError("内部服务器错误，请重试")
    print(f"session check response: {response}")
    return True


def generate_session(wx_app_id, wx_secret, code):
    url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + wx_app_id + '&secret=' + wx_secret + '&js_code=' + code + '&grant_type=authorization_code'
    result = Http.get(url)
    print(result)
    error_code = result.get('errcode', 0)
    if error_code == 40029:
        raise AuthFailed(msg='传入非法code')
    elif error_code == 40163:
        raise AuthFailed(msg='code已被使用')
    elif error_code == 40226:
        raise AuthFailed(msg='监测为高风险等级用户，拒绝登录，请联系管理员')
    return result


if __name__ == '__main__':
    MINA_APP_ID = 'wx83e254dbcbab0ee7'
    MINA_APP_SECRET = 'd6b523adb7da85c9b3601d371ca5fa38'

    # get_access_token(MINA_APP_ID, MINA_APP_SECRET)
    access_token = '83_gLoYOdrkr-whbvdBtthSNg6iU2XRU_eZKX0uAjuKX4_KhAA9YNJYFo6-bhSwKslJAsCMGhAQa2oUIinVwTSPCrKhkFYrWJ8BZy6MmaAA0sFAFhA_fX2nBuEqw3kEBAbAIAVSR'
    session = 'lFF29NEk6Sq8fU7DrCwFHg=='
    open_id = 'o0tOY5XgEQI2O_dvPig99kIG7kig'
    session_check(session, access_token, open_id)
    "session check response: {'errcode': 40003, 'errmsg': 'invalid openid rid: 66d00a2c-5fc24447-54fe5ceb'}"
    # get_access_token()
